<?php

namespace App\Models;

use App\Events\Out\EventInviteOneOnOneShareCreated;
use Carbon\Carbon;
use App\Facades\KafkaBridge;
use Illuminate\Database\Eloquent\SoftDeletes;

class InviteOneOnOneShare extends BaseModels
{
    use SoftDeletes;

    protected $table = 'invite_one_on_one_shares';
    protected $primaryKey = 'id';

    const SHARE_CODE_PREFIX = 'ONE_ON_ONE';

    const STATUS_OK = 0;
    const STATUS_DONE = 1;//抢完
    const STATUS_EXPIRED = 2;//过期
    const STATUS_ACCEPTED = 3;//已领取

    const TOTAL_NUM = 3;

    const EXPIRE_DAYS = 30;

    public function getId()
    {
        return $this->id;
    }

    public function getStudentId()
    {
        return $this->student_id;
    }

    public function setStudentId($value)
    {
        $this->student_id = $value;
    }

    public function getShareCode()
    {
        return $this->share_code;
    }

    public function setShareCode($value)
    {
        $this->share_code = $value;
    }

    public function getAcceptNum()
    {
        return $this->accepted_num;
    }

    public function increaseAcceptNum($value = 1)
    {
        $this->accepted_num += $value;
    }

    public function getCreatedAt()
    {
        return $this->created_at;
    }

    public function setCreatedAt($value)
    {
        $this->created_at = $value;
    }

    public function getExpiredAt()
    {
        return $this->expired_at;
    }

    public function setExpiredAt($value)
    {
        $this->expired_at = $value;
    }

    public function getStatus()
    {
        return $this->status;
    }

    public function setStatus($value)
    {
        $this->status = $value;
    }

    public function checkShareIsExpired()
    {
        if ($this->getStatus() == self::STATUS_EXPIRED) {
            return true;
        }

        if (Carbon::now() >= $this->getExpiredAt()) {
            $this->setStatus(self::STATUS_EXPIRED);
            $this->save();
            return true;
        }

        return false;
    }

    public static function createShareByStudentIdAndNotify($studentId)
    {
        $studentShare = InviteOneOnOneShare::where('student_id', $studentId)->first();
        if (!empty($studentShare)) {
            return ;
        }

        $studentShare = new InviteOneOnOneShare();
        $studentShare->setStudentId($studentId);
        $studentShare->setShareCode(uniqid(InviteOneOnOneShare::SHARE_CODE_PREFIX));
        $studentShare->setExpiredAt(Carbon::now()->addDays(InviteOneOnOneShare::EXPIRE_DAYS));
        $studentShare->save();

        $event = new EventInviteOneOnOneShareCreated();
        $event->studentId = $studentId;
        $event->shareCode = $studentShare->getShareCode();
        $event->expiredAt = $studentShare->getExpiredAt()->getTimestamp();
        KafkaBridge::push($event);
    }
}


